package com.sgb.kjwl.view.ui.activity.transport.company;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityInvitationFleetBinding;
import com.sgb.kjwl.model.entity.transport.AttachmentListEntity;
import com.sgb.kjwl.model.entity.transport.TeamRespVoEntity;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.adapter.transport.InvitationFleetItemAdapter;
import com.sgb.kjwl.viewmodel.transport.InvitationFleetModel;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * author:熊丽
 * createDate:2021/10/9 16:54
 * introduce:2.1.3企业新增邀请车队
 * modifier:xxx
 * modifiyDate:
 * modifiyContent:
 */
public class InvitationFleetActivity extends AppActivity {
    ActivityInvitationFleetBinding mbinding;
    InvitationFleetModel mfleetModel;
    private List<AttachmentListEntity> mList;
    private InvitationFleetItemAdapter mAdapter;
    private int mState;
    private int mPage = 1;
    private int current=0;

    public static void start(Context context) {
        Intent intent = new Intent(context, InvitationFleetActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }
    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mbinding = DataBindingUtil.setContentView(this, R.layout.activity_invitation_fleet);
        mfleetModel = new ViewModelProvider(this).get(InvitationFleetModel.class);
        mbinding.includeTitle.titleView.setText("邀请挂靠车队");
        mbinding.etView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mbinding.includeTitle.ivBack.setOnClickListener(this::onMultiClick);
        mbinding.tvSearch.setOnClickListener(this::onMultiClick);
        initRecycler();
        initEvent();
    }
    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new InvitationFleetItemAdapter(mList);
        mbinding.rvInvitationFleet.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (getActivity() != null) {
            DividerDecoration.builder(this)
                    .colorRes(R.color.color_F5F5F5)
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .insets(DensityUtils.dip2px(getActivity(),14), DensityUtils.dip2px(getActivity(),14))
                    .build()
                    .addTo(mbinding.rvInvitationFleet);
        }
        mAdapter.bindToRecyclerView(mbinding.rvInvitationFleet);
    }
    private void initEvent() {
        mbinding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mbinding.etView.setText("");
                mList.clear();
                refreshUIByData(new ListResponse<>());
            }
        });
        mbinding.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mbinding.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    mbinding.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mbinding.srlInvitationFleet.setEnableRefresh(false);
        mbinding.srlInvitationFleet.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                mfleetModel.getInvitationList(getActivity(),mbinding.etView.getText().toString().trim(),mPage, mState);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            AttachmentListEntity info = mList.get(position);
            itemClick(view, info,position);
        });
        //接口回调
        mfleetModel.ldlist.observe(this, this::refreshUIByData);
        mfleetModel.ldadd.observe(this,success->{
            if (success!=null){
                MToast.showToast(this,"邀请成功");
                mList.get(success).setIsAdd(1);
                mList.get(success).setLinkState(1);
                mAdapter.notifyItemChanged(success);
            //  refreshData();
            }
        });
    }

    @Override
    public void onMultiClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_search:
                closeKeybord();
                mPage = 1;
                mfleetModel.getInvitationList(this, mbinding.etView.getText().toString().trim(),mPage, mState);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }
    /**
     * 列表按钮点击事件
     */
    private void itemClick(View view, AttachmentListEntity info,int position) {
        if (view.getId() == R.id.tv_item_invitation_edit) {
            TeamRespVoEntity teamRespVoEntity = new TeamRespVoEntity();
            teamRespVoEntity.setName(info.getName());
            teamRespVoEntity.setNo(info.getNo());
            teamRespVoEntity.setContact(info.getContact());
            teamRespVoEntity.setPhone(info.getPhone());
            mfleetModel.addOrUpdateAnchor(this,teamRespVoEntity,position);
        }else if (view.getId()==R.id.cl_fleet_item){
            FleetDetailsActivity.start(this,info.getNo());
        }
    }
    public void refreshData() {
        if (mAdapter != null) {
            mPage = 1;
            mfleetModel.getInvitationList(getActivity(), mbinding.etView.getText().toString().trim(),mPage, mState);
        }
    }
    /**
     * 同步数据
     */
    private void refreshUIByData(ListResponse<List<AttachmentListEntity>> listResponse) {
        mbinding.srlInvitationFleet.finishRefresh();
        mbinding.srlInvitationFleet.finishLoadMore();
        if (listResponse == null) {
            if (mPage==1){
                mAdapter.setEmptyView(R.layout.layout_empty_view);
            }
            return;
        }
        //设置数据
        if (mPage == 1) {
            mList.clear();
        }
        current=listResponse.getCurrentPage();
        if (listResponse.getList() != null &&listResponse.getList().size()>0) {
            mList.addAll(listResponse.getList());
        }
        if (ArrayUtil.isNullOrEmpty(mList)) {
            mAdapter.setEmptyView(R.layout.layout_empty_view);
        }
        mAdapter.notifyDataSetChanged();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(GoodsManageEvent event) {
        //货源管理页面事件
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_AFFILIATED_SUCCESS) {
            refreshData();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
